/* eslint-disable */
/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue';
import Router from 'vue-router';
import http from '@/utils/httpRequest';
import { clearLoginInfo } from '@/utils';

Vue.use(Router);

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  {
    path: '/404',
    component: () => import('@/views/common/404'),
    name: '404',
    meta: { title: '404未找到' },
  },
  {
    path: '/login',
    component: () => import('@/views/common/login'),
    name: 'login',
    meta: { title: '登录' },
  },
];

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: () => import('@/views/main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    {
      path: '/home',
      component: () => import('@/views/common/home'),
      name: 'home',
      meta: { title: '首页' },
    },
  ],
  beforeEnter(to, from, next) {
    if (to.path === 'test') {
      next();
    } else {
      // let token = Vue.cookie.get('token');
      let token = sessionStorage.getItem('token') || Vue.cookie.get('token');
      if (!token || !/\S/.test(token)) {
        clearLoginInfo();
        next({ name: 'login' });
      }
      next();
    }
  },
};

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat([mainRoutes]),
});

router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  const globalPathList = globalRoutes.map((item) => item.path);
  if (router.options.isAddDynamicMenuRoutes || globalPathList.includes(to.path)) {
    next();
  } else {
    http({
      url: http.adornUrl('/sys/menu/nav'),
      method: 'get',
      params: http.adornParams(),
    })
      .then(({ data }) => {
        if (data && data.code === 0) {
          mainRoutes.name = 'main-dynamic';
          mainRoutes.children = menuTreeToRoutes(data.menuList);
          router.addRoutes([mainRoutes, { path: '*', redirect: { name: '404' } }]);
          sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || []));

          router.options.isAddDynamicMenuRoutes = true;
          sessionStorage.setItem('menuList', JSON.stringify(data.menuList || []));
          sessionStorage.setItem('permissions', JSON.stringify(data.permissions || []));
          router.push({ ...to, replace: true }).then(() => {});
        } else {
          sessionStorage.setItem('menuList', '[]');
          sessionStorage.setItem('permissions', '[]');
          next();
        }
      })
      .catch((e) => {
        console.error(e);
      });
  }
});

function treeToList(tree) {
  const setItem = (treeData, listData) => {
    treeData.forEach((item) => {
      if (item.list && item.list.length > 0) {
        setItem(item.list, listData);
      } else {
        listData.push(item);
      }
    });

    return listData;
  };

  return setItem(tree, []);
}

function menuTreeToRoutes(menuTree) {
  const menuList = treeToList(menuTree);
  return menuList.map((menu) => {
    menu.url = menu.url.replace(/^\//, '');
    let route;
    // url以http[s]://开头, 通过iframe展示
    if (/^http[s]?:\/\/.*/.test(menu.url)) {
      route = {
        path: `i-${menu.menuId}`,
        name: `i-${menu.menuId}`,
        iframeUrl: menu.url,
		meta: {
          menuId: menu.menuId,
          title: menu.name,
          isDynamic: true,
          isTab: true,
          iframeUrl: '',
        },
      };
    } else {
      route = {
        path: menu.url.replace('/', '-'),
        name: menu.url.replace('/', '-'),
        meta: {
          menuId: menu.menuId,
          title: menu.name,
          isDynamic: true,
          isTab: true,
          iframeUrl: '',
        },
        component: () => import(`@/views/modules/${menu.url}`),
      };
    }

    return route;
  });
}

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};
export default router;
